/**
 * @class LocalDB
 * @description Class that initialises the Database and has the Global funcions
 */
var LocalDB = function()
{
	var DB;
	var tableArray;

	/**
	 * Get the DB Connection to make actions on the Database
	 *
	 * @return DB LocalDB
	 */
	this.getDBConnection = function()
	{
		return DB;
	}

	/**
	 * Initialize the local DB
	 */
	this.initDB = function()
	{
		// initialize all tables
		tableArray = this.initTables();

		try {
			//Check whether this browser supports local databases
			if(!window.openDatabase){
				alert("Uw browser ondersteunt geen local databases. Gebruik Chrome of Safari!");
			}else {
				//Params for local DB
				var shortName = 'DB';
				var version = '1.0';
				var displayName = 'DB Web & Mobile';
				var maxsize = 100000;

				//Create the DB with above params
				DB = openDatabase(shortName, version, displayName, maxsize);

				//Create all tables
				this.createAllTables();
			}
		}
		catch (e)
		{
			if (e == 2) {
				// Version number mismatch.
				console.log("Invalid database version.");
			} else {
				console.log("Unknown error "+e+".");
			}
			return;
		}
	}

	/**
	 * Initialize the tables
	 */
	this.initTables = function()
	{
		//The needed variables
		var tableArray = new Array();
		var tableName = "";
		var columnArray = new Array();

		// New table: users
		tableName = "users";
		columnArray.push("userId INTEGER NOT NULL PRIMARY KEY");
		columnArray.push("username VARCHAR(60) NOT NULL");
		columnArray.push("age VARCHAR(3) NOT NULL");
		columnArray.push("image VARCHAR(100) NOT NULL");
		columnArray.push("gender VARCHAR(3) NOT NULL");
		columnArray.push("playcount VARCHAR(20) NOT NULL");
		columnArray.push("registerdate VARCHAR(20) NOT NULL");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		// End of users table


		// New table: friends
		tableName = "friends";
		columnArray.push("connectionId INTEGER NOT NULL PRIMARY KEY");
		columnArray.push("username VARCHAR(60) NOT NULL");
		columnArray.push("friendUsername VARCHAR(60) NOT NULL");
		columnArray.push("UNIQUE(username, friendUsername)");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of friends table


		// New table: comparisons
		tableName = "comparisons";
		columnArray.push("comparisonId INTEGER NOT NULL PRIMARY KEY");
		columnArray.push("username VARCHAR(60) NOT NULL");
		columnArray.push("friendUsername VARCHAR(60) NOT NULL");
		columnArray.push("value FLOAT NOT NULL");
		columnArray.push("UNIQUE(username, friendUsername)");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of comparisons table


		// New table: comparisonArtists
		tableName = "comparisonArtists";
		columnArray.push("comparisonId INTEGER NOT NULL");
		columnArray.push("artistName VARCHAR(60) NOT NULL");
		columnArray.push("UNIQUE(comparisonId, artistName)");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of comparisonArtists table


		// New table: artists
		tableName = "artists";
		columnArray.push("artistId VARCHAR(60) NOT NULL PRIMARY KEY");
		columnArray.push("name VARCHAR(60) NOT NULL");
		columnArray.push("image VARCHAR(100) NOT NULL");
		columnArray.push("url VARCHAR(100) NOT NULL");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of artists table


		// New table: albums
		tableName = "albums";
		columnArray.push("albumId VARCHAR(60) NOT NULL PRIMARY KEY");
		columnArray.push("artistId INTEGER NOT NULL");
		columnArray.push("name VARCHAR(60) NOT NULL");
		columnArray.push("image VARCHAR(100) NOT NULL");
		columnArray.push("url VARCHAR(100) NOT NULL");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of albums table


		// New table: userArtists
		tableName = "userArtists";
		columnArray.push("userArtistId INTEGER NOT NULL PRIMARY KEY");
		columnArray.push("userId INTEGER NOT NULL");
		columnArray.push("artistId VARCHAR(60) NOT NULL");
		columnArray.push("UNIQUE(userId, artistId)");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of userArtists table


		// New table: events
		tableName = "events";
		columnArray.push("eventId INTEGER NOT NULL PRIMARY KEY");
		columnArray.push("userId INTEGER NOT NULL");
		columnArray.push("friendId INTEGER NOT NULL");
		columnArray.push("name VARCHAR(100) NOT NULL");
		columnArray.push("date DATETIME NOT NULL");

		// Add the table to the array
		tableArray.push(new Array(tableName, columnArray));

		//Clear the columns
		columnArray = [];

		//End of events table

		return tableArray;
	}

	/**
	 * Create all the tables
	 */
	this.createAllTables = function()
	{
		DB.transaction
		(
			function (t)
			{
				var tableName = null;
				var columns = [];
				var columnsQuery = null;
				var query = null;
				var separator = null;

				for(var i = 0; i < tableArray.length; i ++)
				{
					tableName = tableArray[i][0];
					columnsQuery = "";
					columns = tableArray[i][1];

					for(var j = 0; j < columns.length; j ++)
					{
						if(j == columns.length-1) separator = "";
						else separator = ", ";
						columnsQuery += columns[j]+separator;
					}

					// Build the query
					query = "CREATE TABLE IF NOT EXISTS "+tableName+"("+columnsQuery+")";

					// Execute the query
					t.executeSql(query, []);
				}
			}
		);
	}

	/**
	 * Empty tables
	 */
	this.emptyAllTables = function()
	{
		DB.transaction
		(
			function(t)
			{
				for(var i = 0; i < tableArray.length; i ++)
				{
					// Build the query
					query = "DELETE FROM "+tableArray[i][0];

					// Execute the DELETE query
					t.executeSql(query, []);
				}
			}
		);
	}

	/**
	 *	Drop all the tables from the DB
	 */
	this.dropAllTables = function()
	{
		DB.transaction
		(
			function(t)
			{
				for(var i = 0; i < tableArray.length; i ++)
				{
					// Build the query
					query = "DROP TABLE "+tableArray[i][0];

					// Execute the DELETE query
					t.executeSql(query, []);
				}
			}
		);
	}
}


// Buttons to empty or delete the local DB
$(document).ready(function()
{
	// Button "Empty DB" is clicked
	$("#emptyDB").click(function(){
		localDB.emptyAllTables();
	});

	// Button "Drop DB" is clicked
	$("#dropDB").click(function(){
		localDB.dropAllTables();
	});
});